from fastapi import FastAPI, Depends, HTTPException, status, Security,Request
from fastapi.security import APIKeyHeader
from fastapi.openapi.utils import get_openapi
import time
app = FastAPI()


# 定义一个 APIKeyHeader 实例，用于获取访问令牌
api_key_header = APIKeyHeader(name="Authorization", auto_error=False)

# 模拟的用户数据，实际情况下需要从数据库或其他地方获取
fake_users_db = {
    "user": {
        "username": "user",
        "password": "password",
    }
}

# 身份验证函数，用于验证令牌
async def get_current_user(api_key: str = Security(api_key_header)):
    if api_key != "fake-access-token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
        )
    return api_key

@app.post("/token")
async def login(username: str, password: str):
    if username in fake_users_db and password == fake_users_db[username]["password"]:
        return {"access_token": "fake-access-token", "token_type": "bearer"}
    raise HTTPException(status_code=400, detail="Incorrect username or password")

# 受保护的路由，需要身份验证
@app.get("/items/")
async def read_items():
    return {"token": "fgg", "items": [{"item": "Foo"}, {"item": "Bar"}]}

# 修改默认的Swagger UI配置
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="Custom API",
        version="1.0.0",
        description="This is a very custom OpenAPI schema",
        routes=app.routes,
    )
    openapi_schema["components"]["securitySchemes"] = {
        "ApiKeyAuth": {
            "type": "apiKey",
            "in": "header",
            "name": "Authorization"
        }
    }
    openapi_schema["security"] = [{"ApiKeyAuth": []}]
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

# 配置CORS以允许跨源请求（例如从本地主机访问API）
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    # (b'authorization', b'Bearer woshiqingqiutou')
    header = request.headers
    print("csrftoken", header.keys(), header.values())
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    print("本次耗时", process_time)
    return response


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8001)
